package com.pojoin.cms.face;

import java.util.HashSet;
import java.util.Set;

import com.pojoin.cms.dao.RoleDao;
import com.pojoin.cms.dao.UserDao;
import com.pojoin.cms.domain.Role;
import com.pojoin.cms.domain.User;
import com.pojoin.cms.domain.alter.UserAlter;
import com.pojoin.cms.domain.form.UserForm;
import com.pojoin.cms.exception.CmsException;
import com.pojoin.cms.util.SpringContext;

public class UserFaceLocal extends UserAlter implements UserFace {
	
	private UserDao userDao;
	
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public boolean isPersistenceAvailable() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void delete() throws CmsException {
//		this.deleted = 1;
//		this.userDao.update(this);
		this.userDao.del(this.userId);

	}

	@Override
	public void flush() throws CmsException {
		this.userDao.update(this);

	}

	@Override
	public void reload() throws CmsException {
		this.init(this.userId);
	}
	
	/**
	 * 初始化
	 * @param userId
	 */
	private void init(Long userId){
		User user = this.userDao.findById(userId);
		this.setDeleted(user.getDeleted());
		this.setEmail(user.getEmail());
		this.setNickName(user.getNickName());
		this.setPassword(user.getPassword());
		this.setRemark(user.getRemark());
		this.setRoles(user.getRoles());
	}
	
	public void setUserId(Long userId){
		this.userId = userId;
	}

	@Override
	public void resetRoles(String selectRoleIds) throws CmsException {
		this.getRoles().clear();
		this.setRoles(this.initRolesByIds(selectRoleIds));
		
	}
	

	@Override
	public void update(UserForm user) {
		this.setDeleted(0);
		this.setEmail(user.getEmail());
		this.setNickName(user.getNickName());
		this.setPassword(user.getPassword());
		this.setRemark(user.getRemark());
		this.setUserName(user.getUserName());
		
		this.getRoles().clear();
		this.setRoles(this.initRolesByIds(user.getSelectRoleIds()));
		
	}

	/**
	 * 根据所选的ids初始化roleSet
	 * @param selectRoleIds
	 * @return
	 */
	private Set<Role> initRolesByIds(String selectRoleIds) {
		Set<Role> roleSet = new HashSet<Role>();
		RoleDao roleDao = (RoleDao) SpringContext.getBean("roleDao");
		if(selectRoleIds != null && !"".equals(selectRoleIds)){
			String[] roleIds = selectRoleIds.split(",");
			for(String roleId : roleIds){
				if(roleId != null && !"".equals(roleId)){
					roleSet.add(roleDao.findRoleById(Long.parseLong(roleId)));
				}
			}
		}
		return roleSet;
	}

}
